<template>
  <div class="register_box knife_container">
    <div class="forms">
      <div class="logo_img_box">
        <span class="logo_img">
          <img src="../../images/knife_logo.png" alt="">
        </span>
        <h2 class="memberTit">{{isRegister ? '--欢迎您注册为刀具联盟会员--' : '--请上传企业真实信息--'}}</h2>
      </div>
      <step stage="three" v-if="isRegister"></step>
      <!-- 公司信息 -->
        <div class="form-box" ref="companyRef">
          <div class="form-item">
            <span class="form-span">企业信息</span>
            <input class="form-input el-input__inner" v-model="companyForm.companyName" placeholder="输入您的公司名称" auto-complete="off"  @change="validateMethod(companyForm.companyName, 'companyName')" clearable/>
            <p class="error" v-show="!companyNameError.status && companyNameError.text.length > 0"><i class="el-icon-warning"></i>{{companyNameError.text[0]}}</p>
          </div>
          <div class="form-item">
            <span class="form-span">公司地址</span>
            <el-cascader expand-trigger="hover" ref="address" v-model="companyForm.comAddr" :options="citys" @change="handleChange" :props="props" style="width:100%"></el-cascader>
            <p class="error" v-show="!comAddrError.status && comAddrError.text.length > 0"><i class="el-icon-warning"></i>{{comAddrError.text[0]}}</p>
          </div>
          <div class="form-item">
            <span class="form-span">详细地址</span>
            <input class="form-input el-input__inner" v-model="companyForm.address" placeholder="输入详细地址" auto-complete="off"  @change="validateMethod(companyForm.address, 'address')" clearable/>
            <p class="error" v-show="!addressError.status && addressError.text.length > 0"><i class="el-icon-warning"></i>{{addressError.text[0]}}</p>
          </div>
          <div class="form-item">
            <span class="form-span">上传营业执照</span>
            <el-upload
              v-model="companyForm.businessLicense"
              :before-upload="beforeUpload"
              accept="image/*"
              class="avatar-uploader"
              :http-request="handleHttp"
              :action="baseUrl + '/common/image'"
              :show-file-list="false"
              :on-success="handleAvatarPreview"
              :on-preview="handleAvatarPreview">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <span v-if="imageUrl" class="btn-large-img" @click.stop="isEnlargeimg = true">点击查看大图</span>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <p class="error" v-show="licenseError.status"><i class="el-icon-warning"></i>{{licenseError.text}}</p>
          </div>
          <button class="sureBtn mar-bt12" :class="{'active': companyCertError}" :disabled="!companyCertError" 
          @click="companyCert('companyRef')">确认上传</button>
          <p><el-checkbox v-model="checked">我同意《刀具联盟刀刃具服务条款》</el-checkbox></p>
        </div>
    </div>
    <!-- 大图放大 -->
      <template v-if="isEnlargeimg">
        <div class="v-modal" tabindex="0" style="z-index: 2000;" @click="isEnlargeimg = false"></div>
        <div class="enlargeimg-box">
          <div class="enlargeimg-inner">
            <i class="close el-icon-circle-close-outline" @click="isEnlargeimg = false"></i>
            <img :src="imageUrl" />
          </div>
        </div>
      </template>
  </div>
</template>

<script>
import {CHINESE} from '@/config/regex'
import {addressForAll} from '@/tool/address'
import {prefixImg} from '@/tool/index'
import {Form, FormItem, Button, Input, Upload, Checkbox, Cascader} from 'element-ui'
import {getCompanyCert, uploadImg} from '@/service/get-data'
import {mapState} from 'vuex'
import {step} from '@/components/index'
import {baseUrl} from '@/config/baseUrl'
export default {
  components: {
    elForm: Form,
    elFormItem: FormItem,
    elButton: Button,
    elInput: Input,
    elUpload: Upload,
    elCheckbox: Checkbox,
    elCascader: Cascader,
    step
  },
  data () {
    return {
      companyForm: {
        companyName: '',  // 公司名称
        comAddr: [], // 公司地址
        address: '', // 公司详细地址
        businessLicense: '',  // 营业执照
        province: '', // 省
        provinceCode: '', // 省码
        city: '', // 城市
        cityCode: '', // 城市码
        area: '', // 区域
        areaCode: ''// 区域码
      },
      companyRules: {
        companyName: [{required: true, pattern: CHINESE, message: '请输入正确的公司名称', min: 5, trigger: 'blur'}],
        comAddr: [{required: true, type: 'array', message: '请选择地址', trigger: 'blur'}],
        address: [{required: true, message: '请输入详细地址', trigger: 'blur'}]
      },
      citys: addressForAll, // 省市区三级联动数据
      props: {  // 三级联动建名配置
        value: 'value',
        label: 'label',
        children: 'children'
      },
      imageUrl: '',
      checked: true, // 同意协议,
      companyNameError: { // 公司名称
        status: false,
        text: []
      },
      comAddrError: { // 公司地址
        status: false,
        text: []
      },
      addressError: { // 公司详细地址
        status: false,
        text: []
      },
      isEnlargeimg: false, // 图片放大
      licenseError: {status: false, text: '请上传图片'},
      strategy: {
        companyName: {
          zero: '请输入公司名称',
          rules: [CHINESE],
          texts: ['请输入正确的公司名称']
        },
        comAddr: {
          zero: '请选择地址'
        },
        address: {
          zero: '请输入详细地址'
        }
      },
      isRegister: false, // 是否是注册
      compressImg: '' // 压缩后的图片地址
    }
  },
  methods: {
    // 获取用户信息
    async fetchUserData () {
      this.$store.dispatch('getUserData').then(res => {
        if (res.data.resultCode && res.data.resultCode === 2000) {
          res = res.data
          let obj = res.data
          for (var key in obj) {
            this.companyForm[key] = obj[key] ? obj[key] : ''
            if (key === 'companyName' || key === 'comAddr' || key === 'address') {
              obj[key] && this.validateMethod(obj[key], key)
            }
            if (obj['businessLicense']) {
              this.imageUrl = this.prefixImg + obj['businessLicense']
            }
          }
        }
      })
    },
    // 验证表单字段
    validateMethod (value, type) {
      // debugger
      let strategy = this.strategy
      let error = type + 'Error'
      let zero = strategy[type]['zero']
      let rules = strategy[type]['rules']
      let texts = strategy[type]['texts']
      this[error].text = []
      if (value.length < 1) {
        this[error].status = false
        this[error].text.push(zero)
        return false
      }
      this[error].status = true
      // 不存在 rules
      if (!rules) return
      for (let i = 0; i < rules.length; i++) {
        if (!rules[i].test(value)) {
          this[error].status = false
          this[error].text.push(texts[i])
        }
      }
    },
    beforeUpload (file) {
      let _this = this
      const reg = /^image\/+(JPEG|jpeg|JPG|jpg|png|PNG|gif)$/
      const isImg = reg.test(file.type)
      // const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImg) {
        this.$message.error('上传图片只能是图片格式!')
      }
      // console.log(file, file.size)
      // 调用函数，对图片进行压缩
      this.compress(file, function (ImgBase64) {
        let imgBase64 = ImgBase64 // 存储转换的base64编码
        _this.compressImg = imgBase64 // 显示预览图片
      })
      return isImg
    },
    companyCert (formName) {
      this.validateMethod(this.companyForm.companyName, 'companyName')
      this.validateMethod(this.companyForm.comAddr, 'comAddr')
      this.validateMethod(this.companyForm.address, 'address')
      if (!this.companyNameError.status || !this.comAddrError.status || !this.addressError.status) {
        return false // 阻止表单提交
      }
      if (!this.checked) {
        this.$message({message: '请确认同意条款', type: 'error'})
        return false
      }
      if (!this.companyForm.businessLicense) {
        this.licenseError.status = true
        return false
      }
      this.fetchCompany() // 企业认证
    },
    // 企业信息认证
    async fetchCompany () {
      let area = !this.companyForm.area ? '' : this.companyForm.area
      let areaCode = !this.companyForm.areaCode ? '' : this.companyForm.areaCode
      let res = await getCompanyCert(
        this.companyForm.companyName,
        this.companyForm.province,
        this.companyForm.provinceCode,
        this.companyForm.city,
        this.companyForm.cityCode,
        area,
        areaCode,
        this.companyForm.businessLicense,
        this.companyForm.address,
        this.mobile
      )
      if ((res.data.resultCode && res.data.resultCode === 2000) || res.data.resultCode === 4010) {
        this.$message({
          message: '刀具已经收到您的企业信息, 马上进行审核...',
          type: 'success'
        })
        this.$store.dispatch('getUserData').then(() => {
          this.$router.push({name: 'ComCertUploadResult', params: {type: 'success'}})
        })
      } else {
        this.$message({
          message: res.data.resultMsg
        })
      }
    },
    handleChange () {
      let addrCode = this.companyForm.comAddr
      let addrLabel = this.$refs.address.currentLabels
      this.companyForm.province = addrLabel[0]
      this.companyForm.provinceCode = addrCode[0] // 省码
      this.companyForm.city = addrLabel[1]  // 城市
      this.companyForm.cityCode = addrCode[1]  // 城市码
      this.companyForm.area = addrLabel[1]  // 区域
      this.companyForm.areaCode = addrCode[2] // 区域码
      this.validateMethod(this.companyForm.comAddr, 'comAddr')
    },
    handleAvatarPreview (res, file) {
      this.imageUrl = this.compressImg || URL.createObjectURL(file.raw)
    },
    handleError (err, file, fileList) {
      console.log(err)
    },
    // 上传图片
    async handleHttp (file) {
      let param = new FormData()  // 创建form对象
      param.append('files', file.file, file.name)  // 通过append向form对象添加数据
      let res = await uploadImg(param)
      if (res.data.resultCode && res.data.resultCode === 2000) {
        res = res.data
        this.licenseError.status = false // 隐藏图片
        res.data.map((item, index) => {
          this.companyForm.businessLicense = item.filePath
        })
      }
    },
    // 压缩图片
    async compress (fileObj, callback) {
      let _this = this
      try {
        let reader = new FileReader()
        reader.onload = function (e) {
          // 文件大小小于1Mb直接上传
          if (fileObj.size < 1048576) {
            callback(e.target.result)
            _this.fetchJavaImg(e.target.result)
            return true
          } else {
            // 文件大小大于1Mb压缩后上传
            let image = new Image()
            image.onload = function () {
              let that = this
              let isWild = (that.width / that.height > 768 / 1024) // true调整宽度, false调整高度
              let canvas = document.createElement('canvas')
              let context = canvas.getContext('2d')
              let data = ''
              let quality = 0.8
              if (isWild) {
                canvas.width = 768
                canvas.height = Math.round(768 * that.height / that.width)
              } else {
                canvas.height = 1024
                canvas.width = Math.round(1024 * that.width / that.height)
              }
              context.clearRect(0, 0, canvas.width, canvas.height)
              context.drawImage(this, 0, 0, that.width, that.height, 0, 0, canvas.width, canvas.height)
              data = canvas.toDataURL('image/jpeg', quality)
              // 计算base64 图片的大小
              // var str = data.substring(22)
              // var equalIndex = str.indexOf('=')
              // if (str.indexOf('=') > 0) {
              //   str = str.substring(0, equalIndex)
              // }
              // var strLen = str.length
              // var filelength = parseInt(strLen - (strLen / 8) * 2)
              // 压缩完成执行回调
              callback(data)
              _this.fetchJavaImg(data)
            }
            image.setAttribute('src', e.target.result)
          }
        }
        reader.readAsDataURL(fileObj)
      } catch (e) {
        console.log('压缩失败')
      }
    },
    // base64 转 Blob 对象
    dataURItoBlob (dataURI) {
      var byteString = atob(dataURI.split(',')[1]) // atob window的api 解码
      var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
      var ab = new ArrayBuffer(byteString.length)
      var ia = new Uint8Array(ab)
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i)
      }
      return new Blob([ab], {type: mimeString})
    },
    // 提交图片
    async fetchJavaImg (dataURI) {
      let param = new FormData() // 创建form对象
      let file = this.dataURItoBlob(dataURI)
      param.append('files', file, 'image.jpeg') // 通过append向form对象添加数据
      let res = await uploadImg(param)
      if (res.data.resultCode && res.data.resultCode === 2000) {
        res = res.data
        this.licenseError.status = false // 隐藏图片
        res.data.map((item, index) => {
          this.companyForm.businessLicense = item.filePath
        })
      }
    }
  },
  mounted () {
    this.fetchUserData()
  },
  computed: {
    ...mapState({
      mobile: state => state.user.mobile
    }),
    companyCertError () {
      return this.companyNameError.status && this.comAddrError.status && this.addressError.status
    },
    baseUrl () {
      return baseUrl
    },
    prefixImg () {
      return prefixImg
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (from.name === 'Register') {
        vm.isRegister = true
      }
    })
  }
}
</script>

<style lang="scss" scoped>
  .register_box{
    margin-top: 45px;
    margin-bottom: 60px;
  }
  .forms{
    background: #ffffff;
    border-radius: 2px;
    margin-top: 20px;
    padding-bottom: 80px;
  }
  .logo_img_box{
    padding-top: 100px;
    text-align: center;
    .logo_img{
      display: inline-block;
      width: 180px;
      & > img{
        width: 100%;
      }
    }
  }
  .memberTit{
    font-size: 18px;
    color: #FFCC00;
    padding-bottom: 75px;
    padding-top: 20px;
  }
  .form_box{
    width: 350px;
    margin: 0 auto 30px;
  }
  .avatar-uploader {
      width: 178px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      &:hover{
        border-color: #409EFF;
      }
    }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
    .btn-large-img{
    position: absolute;
    bottom: 0;
    width: 100%;
    display: inline-block;
    left: 0;
    background: rgba(0,0,0,0.5);
    padding: 10px 0;
    font-size: 12px;
    color: #fff;
    cursor: pointer;
    transform: translateY(35px);
    transition: transform 0.5s linear;
  }
  .avatar-uploader:hover  .btn-large-img{
    transform: translateY(0)
  }
  .form-item{
    position: relative;
    .error{
      position: absolute;
      left: 360px;
      width: 100%;
      top: 50px;
      i{
        margin-right: 8px;
      }
    }
  }
  .form-box{
    width: 350px;
    margin: 0 auto;
    .form-span{
      line-height: 2.5;
    }
    .form-input{
      margin-bottom: 10px;
    }
  }
  .sureBtn{
    display: inline-block;
    cursor: pointer;
    color: #BBBBBB;
    background: #E6E6E6;
    font-size: 16px;
    width: 100%;
    height: 50px;
    text-align: center;
    line-height: 50px;
    margin-top: 22px;
    border:none;
    &.active{
      background: #FFE100;
      color: #303030;
    }
  }
  .mar-bt12{
    margin-bottom: 12px;
  }
  .error{
    color: #ff0000;
    font-size: 14px;
    .B-error{
      font-size:12px;
      color: #6c6b6b;
      padding-left: 20px;
    }
  }
  .enlargeimg-box{
    width: 500px;
    height: 500px;
    z-index: 2001;
    transform: translate(-50%, -50%);
    position: absolute;
    top: 50%;
    left: 50%;
    img{
      width: 100%;
    }
    .enlargeimg-inner{
      position:relative;
      .close{
        position: absolute;
        cursor: pointer;
        top: -16px;
        right: -23px;
        font-size: 23px;
        color: #fff;
      }
    }
  }
  .v-modal{
    opacity: 0.7!important;
  }
</style>
